package com.qhgrain.app.util;

import java.util.ArrayList;
import java.util.List;

import com.paas.base.modules.utils.lang.StringUtil;
import com.qhgrain.app.vo.MenuVo;

public class MenuTreeUtil {

	/**
	 * 将菜单按父子归类成树形结构
	 * @param menus
	 * @return
	 */
	private static List<MenuVo> result = null;
	private static List<MenuVo> dataList = null;
	
	private static String space= "&nbsp;&nbsp;&nbsp;";
	
	private static String treeChar = "┣";
	
	
	public static List<MenuVo> buildTree(List<MenuVo> menus,boolean isNeedTreeChar,boolean isNeedSpace){
		result = new ArrayList<MenuVo>();
		dataList = menus;
		
		for(MenuVo m : menus){
			if(StringUtil.isBlank(m.getParentMenuId())){
				result.add(m);
				build(m,isNeedTreeChar,isNeedSpace);
			}
		}
		return result;
	}
	
	private static void build(MenuVo pvo,boolean isNeedTreeChar,boolean isNeedSpace){
		List<MenuVo> list = getChild(pvo);
		if(!list.isEmpty()){
			for(MenuVo m : list){
				if(isNeedTreeChar || isNeedSpace) makeMenuTreeName(m,isNeedTreeChar,isNeedSpace);
				result.add(m);
				build(m,isNeedTreeChar,isNeedSpace);
			}
		}
	}
	
	private static List<MenuVo> getChild(MenuVo pvo){
		List<MenuVo> list = new ArrayList<MenuVo>();
		for(MenuVo m : dataList){
			if(pvo.getId().equals(m.getParentMenuId())){
				list.add(m);
			}
		}
		return list;
	}
	private static void makeMenuTreeName(MenuVo menu,boolean isNeedTreeChar,boolean isNeedSpace){
		if(StringUtil.isNotBlank(menu.getParentMenuId())){
			String name =""; 
			if(isNeedSpace){
				int level = Integer.parseInt(menu.getLevelNum());
				for(int i=1;i<level;i++	){
					name += space;
				}
			}
			
			if(isNeedTreeChar) name= name + treeChar;
			name = name+menu.getName();
			menu.setName(name);
		}
	}
	public static void main(String[] args) {
		List<MenuVo> list = new ArrayList<MenuVo>();
		list.add(new MenuVo("100","菜单100",null,"1"));
		list.add(new MenuVo("200","菜单200",null,"1"));
		
		list.add(new MenuVo("101","菜单101","100","2"));
		list.add(new MenuVo("201","菜单201","200","2"));
		
		list.add(new MenuVo("102","菜单102","100","2"));
		list.add(new MenuVo("113","菜单113","101","3"));
		
		buildTree(list,false,true);
		
		for(MenuVo m : result){
			System.out.println(m.getName()+"\t"+m.getId()+"\t"+m.getParentMenuId());
		}
	}
}
